package com.macken.wowoadmin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.macken.wowadmin.dao.AdminDao;
import com.macken.wowadmin.dao.HostDao;
import com.macken.wowadmin.entity.AdminInfo;
import com.macken.wowadmin.entity.HostInfo;

@Controller
@RequestMapping("/admin/")
public class AdminController {

	AdminDao adminDao = AdminDao.instance;
	HostDao hostDao = HostDao.instance;

	@RequestMapping("index.do")
	public String index(HttpServletRequest request) {
		List<AdminInfo> admins = adminDao.getAllAdminList();
		request.setAttribute("admins", admins);
		return "/admin/admin.jsp";
	}
	@RequestMapping("add.do")
	public String add(HttpServletRequest request) {
		List<HostInfo> hosts = hostDao.getHostList();
		request.setAttribute("hosts", hosts);
		return "/admin/addadmin.jsp";
	}

	@RequestMapping("modify.do")
	public String modify(HttpServletRequest req, @RequestParam int aid) {
		AdminInfo admin = adminDao.getAdminById(aid);
		req.setAttribute("admin", admin);
		List<HostInfo> hosts = hostDao.getHostList();
		req.setAttribute("hosts", hosts);
		return "/admin/addadmin.jsp";
	}

	@RequestMapping("del.do")
	public void del(@RequestParam int aid, HttpServletResponse response) throws Exception {
		adminDao.del(aid);
		response.sendRedirect("/admin/index.do");
		return;
	}

	@RequestMapping("save.do")
	public void save(HttpServletResponse response, @RequestParam(defaultValue = "-1") String adminid,
			@RequestParam int hostid, @RequestParam String name, @RequestParam String pass, @RequestParam String note)
			throws Exception {
		boolean isAdd = true;
		AdminInfo admin;
		if (adminid.equals("-1") || adminid.trim().equals("")) {
			admin = new AdminInfo();
		} else {
			int aid = Integer.valueOf(adminid);
			admin = adminDao.getAdminById(aid);
			if (admin == null) {
				admin = new AdminInfo();
			} else {
				isAdd = false;
			}
		}

		admin.setHostId(hostid);
		admin.setAdminName(name);
		admin.setAdminPass(pass);
		admin.setNote(note);
		if (isAdd) {
			adminDao.add(admin);
		} else {
			adminDao.update(admin);
		}
		response.sendRedirect("/admin/index.do");
		return;
	}

}
